import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Select, DatePicker, Checkbox, Tooltip,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import {ellipsis, afterCloseModal, DescriptionItem, download, formateObjToParamStr, getLastDay} from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import request from "@/utils/request";
import config from "@/config/config";
const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ staff_report2, loading,global }) => ({
  staff_report2,
  global,
  loading: loading.models.staffs,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_users:[],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      staff_report2: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        staff_report2: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'staff_report2/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'staff_report2/changeLoaded',
          });
          dispatch({
            type: 'staff_report2/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    const that=this;
    request(`/revenue_statistics_users`,{
      method:'GET',
    }).then((response)=>{
      if(response.status===200){
        that.setState({
          all_users:response.data.data
        })
      }

    });
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'staff_report2/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'staff_report2/changeTableY',
    });
  };
  findChildFunc = (cb)=> {
    this.file=cb
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'staff_report2/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      staff_report2: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'员工名称'}>
          {getFieldDecorator('user_ids', {
            initialValue: searchParams.user_ids,
          })(
            <Checkbox.Group style={{ width: '100%' }}>
              {
                this.state.all_users.map((item,index)=>{
                  return   <Checkbox key={index} value={item.id}>{item.username}</Checkbox>
                })
              }

            </Checkbox.Group>
          )}
        </FormItem>
        <br/>
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(searchParams.start_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(searchParams.end_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;
                console.log(fieldsValue)
                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
                  end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),
                });

              });
            }}
          >
            查询
          </Button>
          <Tooltip title={'请先查询一次再导出'}>
            <Button
              className={'btn-green'}
              type="primary"
              icon="export"
              style={{ marginLeft: 8 }}
              onClick={this.handleExportReport}
            >导出报表
            </Button>
          </Tooltip>
        </FormItem>

      </Form>
    );
  }
  handleExportReport=()=>{
    const {
      staff_report2: { searchParams },
    } = this.props;
    console.log('searchParams',searchParams)
    let branch_id=sessionStorage.getItem('branch_id');
    download(`${config.prefix}/user_summary_report_files?Authorization=Bearer ${sessionStorage.getItem('token')}&order_direction=desc&${formateObjToParamStr(
      {...searchParams,
        branch_id})}`)

  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        staff_report2: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
        });

      });
    }
  }
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'staff_report2/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('添加角色成功');
        that.setState({
          addModal: false,
        });
        const {
          staff_report2: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      name: '',
      page: 1,
      per_page: 30,
    });
  };

  render() {
    const that = this;
    const {
      staff_report2: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global:{gridTableW}
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            staff_report2: { meta },
          } = this.props;
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: '用户名',
        width: 200,
        key: 'username',
      },
      {
        name: '开户数量',
        width: 150,
        key: 'open_account_count',
        formatter: (event) => {
          return <span style={{color:'rgb(0,0,0)',fontWeight:'bold'}}>{event.value}</span>
        }
      },
      {
        name: '收费笔数',
        width: 150,
        key: 'charge_count',
        formatter: (event) => {
          return <span style={{color:'rgb(38, 181, 26)',fontWeight:'bold'}}>{event.value}</span>
        }
      },
      {
        name: '收费金额',
        width: 150,
        key: 'charge_amount',
        formatter: (event) => {
          return <span style={{color:'rgb(0, 104, 201)',fontWeight:'bold'}}>{event.value}</span>
        }
      },
    ].map(c => ({  ...defaultColumnProperties,...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if(totalWidth<gridTableW){
      columns[columns.length-1].width=   columns[columns.length-1].width+gridTableW-totalWidth
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>员工统计报表</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'staff_report2/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading&&<Loading />
          }
        </div>


      </div>
    </div>;
  }
}

export default BasicList;
